import pymysql
import json
import sys
import os

sys.path.append('../')
sys.path.append('C:/Users/Ric/Desktop/demo/jsw/Python/apiautotest/Apiautomation')
curPath = os.path.abspath(os.path.dirname(__file__))
from Apiautomation.util.init import handle_ini
from Apiautomation.util.log import run_log as logger



class DB:

    def __init__(self):
        self.connectiondatabase()

    # #打开数据库连接
    # #注意：这里已经假定存在数据库testdb，db指定了连接的数据库，当然这个参数也可以没有
    def connectiondatabase(self):
        try:
            self.conn = pymysql.connect(host = "121.40.189.232",port = 3306,user="root",password="biao8888",database="test",charset="utf8")
        except:
            logger.error("connectDatabase failed")
            return False
        self.cur = self.conn.cursor()
        return True


    # 关闭数据库
    def closedatabase(self):
        # 如果数据打开，则关闭；否则没有操作
        if self.conn and self.cur:
            self.cur.close()
            self.conn.close()
        return True

    # 执行数据库的sq语句,主要用来做增，删，改操作
    def execute(self,sql):
        self.connectiondatabase()
        try:
            if self.conn and self.cur:
                self.cur.execute(sql)
                self.conn.commit()

        except:
            logger.error("execute failed: " + sql)
            self.closedatabase()
            return False
        return True

    # 用来查询表数据
    def select(self,sql):
        try:
            self.connectiondatabase()
            self.cur.execute(sql)
            result = self.cur.fetchall()
            logger.info("select success：" + sql)
            return result
            db.closedatabase()
        except Exception as e:
            logger.error("execute failed：" + sql)
            logger.error(e)
            return (e)
            db.closedatabase()

db = DB()
if __name__ == "__main__":
    db = DB()
    sql = "select * from api;"
    result = db.select(sql)
    print(type(result[0][1]))
    print(result)